package com.wurao.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wurao.entity.Blog;
import com.wurao.entity.Comment;
import com.wurao.service.BlogService;
import com.wurao.service.CommentService;
import com.wurao.util.ResponseUtil;

import net.sf.json.JSONObject;

/**
 * 评论Controller层
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/comment")
public class CommentController {

	@Resource
	private CommentService commentService;

	@Resource
	private BlogService blogService;

	/**
	 * 添加或者修改评论
	 * @param comment	评论
	 * @param imageCode 输入的验证码
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(Comment comment, @RequestParam("imageCode") String imageCode, 
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws Exception {
		//正确验证码
		String sRand=(String) session.getAttribute("sRand");
		
		JSONObject result=new JSONObject();
		int resultTotal=0;//记录
		if(!imageCode.equals(sRand)){
			result.put("success", false);
			result.put("errorInfo", "验证码填写错误!");
		}else{
			String userIp=request.getRemoteAddr();//获取用户ip
			comment.setUserIp(userIp);
			if(comment.getId()==null){
				//添加评论
				resultTotal=commentService.add(comment);
				// 博客的回复次数加1
				Blog blog=blogService.findById(comment.getBlog().getId());//外键
				blog.setReplyHit(blog.getReplyHit()+1);
				System.out.println(blog.getReplyHit()+"____");
				Integer row=blogService.update(blog);//修改
				System.out.println(row+"___");
			}
		}
		
		if(resultTotal>0){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}

}
